//
//  SheetView.m
//  QoilPublic
//
//  Created by SunChao on 17/9/8.
//  Copyright © 2017年 杨凯. All rights reserved.
//



#import "SheetView.h"
#import "GlobalStarCell.h"
#import "DetailStarCell.h"
#import "MarkCell.h"
#import "EvaluateTextCell.h"
#define ConViewH  450
@interface SheetView()<UITableViewDelegate,UITableViewDataSource,StarSelectedDelegate,AdviseTextDelegate>
{
    UIView *_contentView;
    UITableView *_tableView;
    UIButton *_judgeButton;//评价按钮
    NSMutableString *_labelContent;//标签拼接的字符串
    
    BOOL isBad;//差评
    NSString *_badString;//两个星以下的评论内容
    NSArray *_goodTagArr;//好的标签
    NSMutableArray *_goodTagStr;//好的标签字符串
    NSArray *_badTagArr;//坏的标签
    NSMutableArray *_badTagStr;//坏的标签字符串
    BOOL _isHidden;
    
    NSString *_star1;
    NSString *_star2;
    NSString *_star3;
    NSString *_adviseString;
    NSArray *_textArr;
}

@end

@implementation SheetView

- (id)initWithFrame:(CGRect)frame
{
    if (self == [super initWithFrame:frame])
    {
        [self initContent];
    }
    
    return self;
}

- (void)initContent
{
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    //alpha 0.0  白色   alpha 1 ：黑色   alpha 0～1 ：遮罩颜色，逐渐
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.userInteractionEnabled = YES;
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disMissView)]];
    
    if (_contentView == nil)
    {
        _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight - ConViewH, kScreenWidth, ConViewH)];
        _contentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self addSubview:_contentView];
    }
    _goodTagStr = [NSMutableArray array];
    _badTagStr = [NSMutableArray array];
    _badString = @"";
    [self createTableView];
    [self gainStarText];
    _isHidden = YES;
    

    
}

-(void)createTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, ConViewH) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollEnabled = NO;
    [_contentView addSubview:_tableView];
    
//    [_tableView registerNib:[UINib nibWithNibName:@"StartViewCell" bundle:nil] forCellReuseIdentifier:@"StartViewCell"];
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
//    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 8, kScreenWidth, 25)];
//    label.font = [UIFont systemFontOfSize:18];
//    label.text = @"总体评价";
//    label.textAlignment = NSTextAlignmentCenter;
//    [view addSubview:label];
//    _tableView.tableHeaderView = view;
    [_tableView registerNib:[UINib nibWithNibName:@"GlobalStarCell" bundle:nil] forCellReuseIdentifier:@"GlobalStarCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"DetailStarCell" bundle:nil] forCellReuseIdentifier:@"DetailStarCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"MarkCell" bundle:nil] forCellReuseIdentifier:@"MarkCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"EvaluateTextCell" bundle:nil] forCellReuseIdentifier:@"EvaluateTextCell"];
    _judgeButton = [QViewUtility createButtonWithFrame:CGRectMake(0,ConViewH-50, kScreenWidth,50) font:17 title:@"提交" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    
    [_judgeButton blueStyle];
    
    [_judgeButton addTarget:self action:@selector(judgeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_contentView addSubview:_judgeButton];

}

#pragma mark--星级文字
- (void)gainStarText{
    
    NSString *url = [QParamService urlWithAction:@"order/getEvalType"];
    NSDictionary *params = [QParamService GainStarText];
    [QViewUtility showMBHudToView:self hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            _textArr = [basModel.items objectForKey:@"list"];
            [_tableView reloadData];
            
        }else{
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

#pragma mark--提交评价
- (void)judgeButtonAction{
    
    
    if (_star1 == nil && _star2 == nil && _star3 == nil) {
        
        _adviseString = @"默认评价";
        
    }
    
    NSString *url = [QParamService urlWithAction:@"order/saveEvaluateOrder"];
    
    if (_star1 == nil || [_star1 isEqualToString:@""]) {
        _star1 = @"5";
    }
    if (_star2 == nil || [_star2 isEqualToString:@""]) {
        _star2 = @"5";
    }
    if (_star3 == nil || [_star3 isEqualToString:@""]) {
        _star3 = @"5";
    }
    
    
   NSArray *dic =  @[
     @{
         @"id" : @"1",
         @"name" : @"服务态度",
         @"stars" : _star1
     },
     @{
         @"id" : @"2",
         @"name" : @"配送速度",
         @"stars" : _star2
     },
     @{
         @"id" : @"3",
         @"name" : @"油品质量",
         @"stars" : _star3
     }
     ];
    NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"jsonStr==%@",jsonStr);
    //NSDictionary *dic = @{@"1":_star1,@"2":_star2,@"3":_star3};
   // NSString *str = [self dictionaryToJson:dic];
    NSDictionary *params = [QParamService CommentOrder:self.orderId content:_adviseString evalJsonstr:jsonStr];
    
    [QViewUtility showMBHudToView:self hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"评价成功" btnTitle:showAlertBtnTitle type:1 myBlock:^{
                [self disMissView];
                UIViewController *vc = [QViewUtility getCurrentVC];
                [vc.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationCommentSuccess object:nil];
            }];

        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        
        return 3;
    }
   
    if (section == 2) {
        return 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        GlobalStarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GlobalStarCell"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;

    }
    if (indexPath.section == 1) {
        NSMutableArray *arr = [NSMutableArray new];
        for (NSDictionary *tmpDic in _textArr) {
            NSString *content = [tmpDic objectForKey:@"content"];
            [arr addObject:content];
        }
        //arr = @[@"服务态度",@"配送速度",@"油品质量"];
        DetailStarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailStarCell"];
        if (arr.count>0) {
             NSString *str  = [arr objectAtIndex:indexPath.row];
             [cell SetupStarViewWith:str indexPathOfRow:indexPath.row canEdit:YES starNum:@"" evaluate:@""];
        }
       
        cell.delegate = self;
        cell.tag = indexPath.row + 1;
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }

    if (indexPath.section == 2) {
        EvaluateTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateTextCell"];
//         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        
        return 50;
    }
    if (indexPath.section == 1) {
        
        return 50;
    }
//    if (indexPath.section == 2) {
//        return 150;
//    }
    if (indexPath.section == 2) {
        return 200;
    }
    return 0;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
//字典转json格式字符串：
- (NSString*)dictionaryToJson:(id)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}




#pragma mark--获取评价标签
//- (void)requestTagData{
//    NSString *url = [QParamService urlWithAction:@"getEvaluationTags"];
//    NSDictionary *param = [QParamService getEvaluationTags];
//    [QViewUtility showMBHudToView:self hideBg:NO];
//    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
//        [QViewUtility hideMBHudToView:self];
//        if(error){
//            return ;
//        }
//        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
//        if([basModel.result isEqualToString:@"success"]){
//            
//            NSDictionary *dic = basModel.items;
//            _goodTagArr = dic[@"listMoreThanThree"];
//            for(NSDictionary *d1 in _goodTagArr){
//                [_goodTagStr addObject:d1[@"content"]];
//            }
//            _badTagArr = dic[@"listMoreThanTwo"];
//            for(NSDictionary *d2 in _badTagArr){
//                [_badTagStr addObject:d2[@"content"]];
//            }
//            [_tableView reloadData];
//        }else{
//            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
//        }
//    }];
//}
- (void)loadMaskView
{
    
}

//展示从底部向上弹出的UIView（包含遮罩）
- (void)showInView:(UIView *)view
{
    if (!view)
    {
        return;
    }
    
    [view addSubview:self];
    [view addSubview:_contentView];
    
    [_contentView setFrame:CGRectMake(0, kScreenHeight, kScreenWidth, ConViewH)];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.alpha = 1.0;
        
        [_contentView setFrame:CGRectMake(0, kScreenHeight - ConViewH, kScreenWidth, ConViewH)];
        
    } completion:nil];
}

//移除从上向底部弹下去的UIView（包含遮罩）
- (void)disMissView
{
    [_contentView setFrame:CGRectMake(0, kScreenHeight - ConViewH, kScreenWidth, ConViewH)];
    [UIView animateWithDuration:0.3f animations:^{
                         
        self.alpha = 0.0;
                         
        [_contentView setFrame:CGRectMake(0, kScreenHeight, kScreenWidth, ConViewH)];
                    
        
    }completion:^(BOOL finished){
                         
        [self removeFromSuperview];
        [_contentView removeFromSuperview];
        
    }];
}

- (void)gainStarWithText: (NSString *) text indexPathOfRow:(NSUInteger )row{
    if (row == 0) {
        _star1 = text;
    }
    if (row == 1) {
        _star2 = text;
    }
    if (row == 2) {
        _star3 = text;
    }
}
-(void)gainStarWithText:(NSString *)text{

    _adviseString = text;
}


@end
